package com.two.screen.water.balance.utils

import android.content.Context
import android.os.Build
import android.text.InputType
import android.view.KeyEvent
import android.view.KeyEvent.*
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import com.two.screen.water.balance.listener.OnMyKeyCallBack
import com.two.screen.water.balance.ui.activity.base.BaseActivity
import java.lang.reflect.Method

/**
 * 自定义键盘
 */
object KeyboardUtil {

    fun onKey(context: Context, et: EditText?, code: Int) {
        if (et == null) return
        hideSystemSoftKeyboard(context, et)
        val editable = et.text
        val start = et.selectionStart

        val textStr = editable.toString()
        var selectStr = textStr.substring(et.selectionStart, et.selectionEnd).length
        CommUtils.println("键盘：", "onKey:$start")
        when (code) {
            -1 -> {
                // 回退
                CommUtils.println("键盘：", "selectStr:$selectStr")
                if (selectStr > 0) {
                    et.setText("")
                } else if (editable != null && editable.isNotEmpty()) {
                    if (start > 0) {
                        editable.delete(start - 1, start)
                    }
                }
            }
            /* 点 */
            -2 -> {
                CommUtils.println("键盘：", "textStr:$textStr.:${textStr.contains(".")}")

                if (selectStr > 0) {
                    et.setText(".")
                    et.setSelection(1)
                } else {
                    if (textStr.contains(".")) return
                    editable!!.insert(start, ".")
                }
            }
            else -> {
                if (selectStr > 0) {
                    et.setText(code.toString())
                    et.setSelection(1)
                } else {
                    editable!!.insert(start, code.toString())
                }

            }
        }
    }

    fun onTextKey(context: Context, et: TextView, code: Int) {
        val editable = et.editableText

        val length = editable.length
        when (code) {
            -1 -> {
                if (length <= 0) return
                // 回退
                editable.delete(length - 1, length)
            }
            /* 点 */
            -2 -> {
                editable!!.insert(length, ".")
            }
            else -> {
                editable!!.insert(length, code.toString())
            }
        }
    }

    fun setSelected(mContext: Context, et: EditText?, isHideKeyboard: Boolean = true) {
        if (et == null) return
        if (isHideKeyboard) hideSystemSoftKeyboard(mContext, et)
        val str = et.text.toString()
        et.setSelectAllOnFocus(true)
        et.selectAll()
        et.setSelection(str.length)
    }

    /**
     * 隐藏系统键盘
     *
     * @param editText
     */
    fun hideSystemSoftKeyboard(context: Context, editText: EditText) {
        val sdkInt = Build.VERSION.SDK_INT
        if (sdkInt >= 11) {
            try {
                val cls = EditText::class.java
                val setShowSoftInputOnFocus: Method = cls.getMethod("setShowSoftInputOnFocus", Boolean::class.javaPrimitiveType)
                setShowSoftInputOnFocus.isAccessible = true
                setShowSoftInputOnFocus.invoke(editText, false)
            } catch (e: SecurityException) {
                e.printStackTrace()
            } catch (e: NoSuchMethodException) {
                e.printStackTrace()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } else {
            editText.inputType = InputType.TYPE_NULL
        }
        // 如果软键盘已经显示，则隐藏
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(editText.windowToken, 0)
    }


    fun onKeyDown(keyCode: Int, event: KeyEvent?, activity: BaseActivity? = null, v: View? = null): Boolean {
        //d("${activity?.javaClass?.simpleName} operate-->")
        //activity?.onKeyDown()
        d("页面监听->keyCode:${keyCode}")
        if (event?.device?.name?.contains("USB", true) != true) return false
        if (event.action == ACTION_DOWN) {//处理触发两次
            when (keyCode) {
                //第一行
                33 -> {
                    d("帐户/E")
                    return true
                }
                133 -> {
                    d("删除/F3")
                    return true
                }
                32 -> {
                    d("修改/D")
                    return true
                }
                134 -> {
                    d("挂起/F4")
                    return true
                }

                //第二行
                46 -> {
                    d("回皮/E")
                    return true
                }
                48 -> {
                    d("1/T")
                    //TODO:数字插入，参考 KeyboardUtilEditOrder.insert()，但是还是要解决拦截usb键盘输入
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_1))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_1))
                    return true
                }
                34 -> {
                    d("2/F")
                    //activity?.onKeyDown(KeyEvent.KEYCODE_2, event)
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_2))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_2))
                    return true
                }
                35 -> {
                    d("3/G")
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_3))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_3))
                    return true
                }

                //第三行
                49 -> {
                    d("回毛/U")
                    return true
                }
                53 -> {
                    d("4/Y")
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_4))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_4))
                    return true
                }
                38 -> {
                    d("5/J")
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_5))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_5))
                    return true
                }
                36 -> {
                    d("6/H")
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_6))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_6))
                    return true
                }

                //第四行
                37 -> {
                    d("去皮/I")
                    return true
                }
                72 -> {
                    d("7/]")
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_7))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_7))
                    return true
                }
                39 -> {
                    d("8/K")
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_8))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_8))
                    return true
                }
                136 -> {
                    d("9/F6")
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_9))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_9))
                    return true
                }

                //第五行
                153 -> {
                    d("清皮/9")
                    return true
                }
                150 -> {
                    d("0/6")
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_0))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_0))
                    return true
                }
                147 -> {
                    d("./3")
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_PERIOD))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_PERIOD))
                    return true
                }
                158 -> {
                    d("过称/.")
                    return true
                }

                //第六行
                152 -> {
                    d("↑/8")
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_DPAD_UP))
                    return true
                }
                149 -> {
                    d("F1/5")
                    return true
                }
                146 -> {
                    d("F2/2")
                    return true
                }
                144 -> {
                    d("F3/0")
                    return true
                }

                //第七行
                44 -> {
                    d("↓/P")
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_DPAD_DOWN))
                    return true
                }
                71 -> {
                    d("F4/[")
                    return true
                }
                74 -> {
                    d("F5/;")
                    return true
                }
                75 -> {
                    d("确认/'")
                    activity?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
                    v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
                    return true
                }
            }
        }

        return false
    }

    fun onNumberDecimalKeyDown(context: Context, et: EditText, listener: OnMyKeyCallBack? = null) {
        et.setOnKeyListener { v, keyCode, event ->
            d("et监听,action:${event.action}")
            if (event?.device?.name?.contains("USB", true) != true) return@setOnKeyListener false
            if (event.action == ACTION_DOWN) {//处理触发两次
                when (keyCode) {
                    133 -> {
                        d("删除/F3")
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_DEL))
                        return@setOnKeyListener true
                    }
                    48 -> {
                        d("1/T")
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_1))
                        return@setOnKeyListener true
                    }
                    34 -> {
                        d("2/F")
                        //activity?.onKeyDown(KeyEvent.KEYCODE_2, event)
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_2))
                        return@setOnKeyListener true
                    }
                    35 -> {
                        d("3/G")
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_3))
                        return@setOnKeyListener true
                    }

                    //第三行
                    53 -> {
                        d("4/Y")
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_4))
                        return@setOnKeyListener true
                    }
                    38 -> {
                        d("5/J")
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_5))
                        return@setOnKeyListener true
                    }
                    36 -> {
                        d("6/H")
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_6))
                        return@setOnKeyListener true
                    }

                    //第四行
                    72 -> {
                        d("7/]")
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_7))
                        return@setOnKeyListener true
                    }
                    39 -> {
                        d("8/K")
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_8))
                        return@setOnKeyListener true
                    }
                    136 -> {
                        d("9/F6")
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_9))
                        return@setOnKeyListener true
                    }

                    //第五行
                    150 -> {
                        d("0/6")
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_0))
                        return@setOnKeyListener true
                    }
                    147 -> {
                        d("./3")
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_PERIOD))
                        return@setOnKeyListener true
                    }

                    //第六行
                    152 -> {
                        d("↑/8")
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT))
                        return@setOnKeyListener true
                    }

                    //第七行
                    44 -> {
                        d("↓/P")
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT))
                        return@setOnKeyListener true
                    }
                    75 -> {
                        d("确认/'")
                        v?.clearFocus()
                        v?.dispatchKeyEvent(KeyEvent(ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
                        listener?.onKeyEnter()
                        return@setOnKeyListener true
                    }
//                    KEYCODE_0, KEYCODE_1, KEYCODE_2, KEYCODE_3, KEYCODE_4, KEYCODE_5, KEYCODE_6, KEYCODE_7, KEYCODE_8, KEYCODE_9,
//                    KEYCODE_DEL, KEYCODE_PERIOD, KEYCODE_DPAD_LEFT, KEYCODE_DPAD_RIGHT, KEYCODE_ENTER -> {
//                        //这里还需要处理true,以防页面再次接收。
//                        true
//                    }
                }
            }
            false
        }
        hideSystemSoftKeyboard(context, et)
    }


    private fun d(str: String) {
        CommUtils.println("KeyboardUtil->", str)
    }
}